package com.luck.emp.sale.logic;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.luck.emp.common.SpOrderNoFour;
import com.luck.emp.common.SpOrderNoTwo;
import com.luck.emp.common.SpWhOrderD;
import com.luck.emp.common.SpWhOrderM;
import com.luck.emp.entity.EmpTProdBase;
import com.luck.emp.entity.EmpTSlOrderD;
import com.luck.emp.entity.EmpTSlOrderM;
import com.luck.emp.entity.EmpTWarehouse;
import com.luck.emp.sale.qry.SaleQry;
import com.luck.pf.common.entity.UserBean;
import com.luck.pf.framework.dao.BaseJdbcDao;
import com.luck.pf.framework.logic.BaseLogic;
import com.luck.pf.util.CriteriaUtil;
import com.luck.pf.util.DateUtil;
import com.luck.pf.util.Page;

/**
 * 说明 Copyright: Copyright (c) 2011 深圳**科技
 * 
 * @author
 * 
 */
public class SaleLogic extends BaseLogic implements ISaleLogic {
	private BaseJdbcDao jdbcDao;

	/**
	 * 查找分页信息
	 */
	public Page findSalePage(SaleQry qry) {
		Criteria criteria = baseDao.createCriteria(EmpTSlOrderM.class);
		CriteriaUtil.addEq(criteria, "slCode", qry.getSlCode());
		CriteriaUtil.addEq(criteria, "billType", qry.getBillType());
		CriteriaUtil.addFullLike(criteria, "custName", qry.getCustName());
		CriteriaUtil.addEq(criteria, "status", qry.getStatus());
		CriteriaUtil.addFullLike(criteria, "tel", qry.getTel());
		criteria.add(Restrictions.between("createDate",
				DateUtil.getStartDateDay(qry.getStartDate()),
				DateUtil.getEndDateDay(qry.getEndDate())));
		criteria.createAlias("dept", "d");
		filterData(criteria, qry.getUserInfo(), "d", null);
		Order order = Order.desc("createDate");
		criteria.addOrder(order);
		return baseDao.pagedQuery(criteria, qry.getPageNo(), qry.getPageSize());
	}

	public BaseJdbcDao getJdbcDao() {
		return jdbcDao;
	}

	public void setJdbcDao(BaseJdbcDao jdbcDao) {
		this.jdbcDao = jdbcDao;
	}

	@Override
	public String saveSale(UserBean userBean, EmpTSlOrderM entity,
			String[] productCodes, String[] priceReals, String[] qtys)
			throws Exception {
		EmpTWarehouse wh = super.baseDao.get(EmpTWarehouse.class,
				entity.getWhCode());
		SpOrderNoTwo ssp = new SpOrderNoTwo(this.jdbcDao.getJdbcTemplate());
		String slCode = ssp.execute(userBean.getDept().getDeptCode(), "SL");
		String billType = "21";// 普通销售单
		entity.setSlCode(slCode);
		entity.setBillType(billType);
		entity.setCreateDate(DateUtil.getDate());
		entity.setCreateUser(userBean.getUser());
		entity.setDeptId(userBean.getDeptId());
		entity.setModiDate(DateUtil.getDate());
		entity.setModiUser(userBean.getUser());
		if (wh.getWhMode().equals("1"))// 如果是简单仓，则直接出库，订单完成
			entity.setStatus("40");
		else
			entity.setStatus("10");// 受理中
		super.baseDao.save(entity);
		// 保存出库单主表,io_type 42:销售出库
		SpWhOrderM sp = new SpWhOrderM(this.jdbcDao.getJdbcTemplate());
		String orderCode = sp.execute(billType, 20L, slCode,
				entity.getWhCode(), null, entity.getCustName(),
				entity.getTel(), entity.getAddr(), entity.getNote(),
				userBean.getUserId(), "42", null, entity.getCustId(),
				entity.getSalemanId());
		// 保存出库单明细
		SpWhOrderD spd = new SpWhOrderD(this.jdbcDao.getJdbcTemplate());
		for (int i = 0, len = productCodes.length; i < len; i++) {
			EmpTProdBase base = super.get(EmpTProdBase.class, productCodes[i]);
			if (StringUtils.isEmpty(qtys[i])) {
				continue;
			}
			EmpTSlOrderD d = new EmpTSlOrderD();
			d.setPrice(base.getSale().getPrice());// 销售价
			d.setRealPrice(Double.parseDouble(priceReals[i]));// 实际销售价
			d.setDiscPrice(d.getPrice() - d.getRealPrice());// 折扣金额
			d.setMeasUnit(base.getMeasUnit());
			d.setProductCode(productCodes[i]);
			d.setQty(Long.parseLong(qtys[i]));
			d.setSlCode(slCode);
			d.setStdPrice(base.getSale().getStdPrice());
			d.setStockPrice(base.getSale().getStockPrice());
			d.setWhCode(entity.getWhCode());
			// 插入订单明细表
			spd.execute(orderCode, productCodes[i], d.getQty(), 0, 0,
					userBean.getUserId(), null);
			super.save(d);
		}

		return null;
	}

	@Override
	public String saveCancelSale(UserBean userBean, EmpTSlOrderM bean)
			throws Exception {
		StringBuffer str = new StringBuffer();
		EmpTSlOrderM sale = super.get(EmpTSlOrderM.class, bean.getSlCode());
		if (!sale.getStatus().equals("40"))// 完成
			str.append("<br>销售单不是完成状态；");
		if (!DateUtil.dateToString(sale.getCreateDate()).equals(
				DateUtil.dateToString(DateUtil.getDate())))
			str.append("<br>只有当日的订单才能撤销；");
		if (StringUtils.isNotBlank(str.toString()))
			throw new Exception(str.toString());
		else {// 进行入库动作
			sale.setStatus("33");// 撤销通过
			sale.setNote(sale.getNote() + "-退货：" + bean.getNote());
			sale.setModiDate(DateUtil.getDate());
			sale.setModiUser(userBean.getUser());
			save(sale);// 保存原销售单
			List<EmpTSlOrderD> ds = findSaleds(sale.getSlCode());
			String billType = "22";// 销售退货单
			// 保存出库单主表,io_type 14:销售退货入库
			SpWhOrderM sp = new SpWhOrderM(this.jdbcDao.getJdbcTemplate());
			String orderCode = sp.execute(billType, 20L, sale.getSlCode(),
					sale.getWhCode(), null, sale.getCustName(), sale.getTel(),
					sale.getAddr(), sale.getNote(), userBean.getUserId(), "14",
					null, sale.getCustId(), sale.getSalemanId());
			// 保存出库单明细
			SpWhOrderD spd = new SpWhOrderD(this.jdbcDao.getJdbcTemplate());
			for (EmpTSlOrderD d : ds) {
				spd.execute(orderCode, d.getProductCode(), d.getQty(),
						d.getQty(), d.getQty(), userBean.getUserId(), null);
			}
		}
		return null;
	}

	@Override
	public String saveThSale(UserBean userBean, SaleQry qry,
			String[] productCodes, String[] priceReals, String[] qtys)
			throws Exception {
		StringBuffer bf = new StringBuffer();
		EmpTSlOrderM sale = super.get(EmpTSlOrderM.class, qry.getSlCode());
		List<EmpTSlOrderD> ds = findSaleds(qry.getSlCode());
		for (int i = 0; i < productCodes.length; i++) {
			for (EmpTSlOrderD d : ds) {// 判断退货数量是否大于销售数量
				if (d.getProductCode().equals(productCodes[i])) {
					Long l = Long.parseLong(qtys[i]);
					if (d.getQty() < l)
						bf.append("商品[" + d.getProduct().getName()
								+ "]退货不能大于销售数量");
				}
			}
		}
		if (StringUtils.isNotBlank(bf.toString()))
			throw new Exception(bf.toString());
		sale.setNote(sale.getNote() + qry.getNote());
		save(sale);
		EmpTSlOrderM entity = new EmpTSlOrderM();
		SpOrderNoFour ssp = new SpOrderNoFour(this.jdbcDao.getJdbcTemplate());
		String slCode = ssp.execute(userBean.getDept().getDeptCode(), "SLTH");
		String billType = "22";// 销售退货单
		entity.setSlCode(slCode);
		entity.setBillType(billType);
		entity.setCreateDate(DateUtil.getDate());
		entity.setCreateUser(userBean.getUser());
		entity.setDeptId(userBean.getDeptId());
		entity.setModiDate(DateUtil.getDate());
		entity.setModiUser(userBean.getUser());
		entity.setOldSlCode(sale.getSlCode());
		entity.setAddr(sale.getAddr());
		entity.setCustName(sale.getCustName());
		entity.setTel(sale.getTel());
		entity.setDiscRatio(sale.getDiscRatio());
		entity.setPayType(sale.getPayType());
		entity.setWhCode(sale.getWhCode());
		entity.setNote(qry.getNote());
		if (sale.getWh().getWhMode().equals("1"))// 如果是简单仓，则直接入库，订单完成
			entity.setStatus("40");
		else
			entity.setStatus("10");// 受理中
		super.baseDao.save(entity);
		// 保存出库单主表,io_type 14:销售退货入库
		SpWhOrderM sp = new SpWhOrderM(this.jdbcDao.getJdbcTemplate());
		String orderCode = sp.execute(billType, 20L, slCode,
				entity.getWhCode(), null, entity.getCustName(),
				entity.getTel(), entity.getAddr(), entity.getNote(),
				userBean.getUserId(), "14", null, entity.getCustId(),
				entity.getSalemanId());
		// 保存入库单明细
		SpWhOrderD spd = new SpWhOrderD(this.jdbcDao.getJdbcTemplate());
		for (int i = 0, len = productCodes.length; i < len; i++) {
			EmpTProdBase base = super.get(EmpTProdBase.class, productCodes[i]);
			if (StringUtils.isEmpty(qtys[i])) {
				continue;
			}
			EmpTSlOrderD d = new EmpTSlOrderD();
			d.setPrice(base.getSale().getPrice());// 销售价
			d.setRealPrice(Double.parseDouble(priceReals[i]));// 实际销售价
			d.setDiscPrice(d.getPrice() - d.getRealPrice());// 折扣金额
			d.setMeasUnit(base.getMeasUnit());
			d.setProductCode(productCodes[i]);
			d.setQty(Long.parseLong(qtys[i]));
			d.setSlCode(slCode);
			d.setStdPrice(base.getSale().getStdPrice());
			d.setStockPrice(base.getSale().getStockPrice());
			d.setWhCode(entity.getWhCode());
			// 插入订单明细表
			spd.execute(orderCode, productCodes[i], d.getQty(), 0, 0,
					userBean.getUserId(), null);
			super.save(d);
		}
		return null;
	}

	public List<EmpTSlOrderD> findSaleds(String slCode) {
		return super.baseDao.find(" From EmpTSlOrderD  WHERE slCode=?", slCode);
	}
}